package com.china.produce.aspect;

import com.alibaba.fastjson.JSON;
import com.china.produce.annotation.Log;
import com.china.produce.enums.BusinessStatus;
import com.china.produce.filter.PropertyPreExcludeFilter;
import com.china.produce.manager.AsyncManager;
import com.china.produce.manager.factory.AsyncFactory;
import com.china.produce.pojo.SysOPerLog;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Objects;
import java.util.Optional;
/**
 *
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2023/3/9
 */
@Aspect
@Component
@Order(-5)
public class LogAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);

    private static final String[] EXCLUDE_FILED = {"password", "oldPassword", "newPassword", "confirmPassword"};

    private static final ThreadLocal<Long> TIME_LOCAL = new NamedThreadLocal<>("cost time");

    @Before(value = "@annotation(controllerLog)")
    public void boBefore(JoinPoint joinPoint, Log controllerLog)
    {
        TIME_LOCAL.set(System.currentTimeMillis());
    }

    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult)
    {
        String params = argsArrayToString(joinPoint.getArgs(), EXCLUDE_FILED);

        LOGGER.info("params : {} args : {}", params, joinPoint.getArgs());

        LOGGER.info("title : {}  businessType : {} result : {}", controllerLog.title(), controllerLog.businessType(), jsonResult);

        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e)
    {
        handleLog(joinPoint, controllerLog, e, null);
    }


    public PropertyPreExcludeFilter excludePropertyPreFilter(String[] excludeParamNames)
    {
        return new PropertyPreExcludeFilter().addExcludes(ArrayUtils.addAll(EXCLUDE_FILED, excludeParamNames));
    }

    private String argsArrayToString(Object[] paramsArray, String[] excludeParamNames)
    {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0)
        {
            for (Object o : paramsArray)
            {
                if (!Objects.isNull(o))
                {
                    try
                    {
                        String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter(excludeParamNames));
                        params += jsonObj.toString() + " ";
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 处理数据异步入库
     *
     * @param joinPoint
     * @param controllerLog
     * @param e
     * @param jsonResult
     */
    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult)
    {
        try {
            SysOPerLog sysOPerLog = new SysOPerLog();
            sysOPerLog.setTitle(controllerLog.title());
            sysOPerLog.setMethod(joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");
            sysOPerLog.setCostTime(System.currentTimeMillis() - TIME_LOCAL.get());
            Optional.ofNullable(controllerLog.businessType()).ifPresent(type -> sysOPerLog.setBusinessType(type));
            sysOPerLog.setJsonResult(JSON.toJSONString(jsonResult));

            if (e != null) {
                sysOPerLog.setStatus(BusinessStatus.FAIL.ordinal());
                sysOPerLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 200));
            }

            LOGGER.info("sysOPerLog {}", sysOPerLog);

            AsyncManager.me().execute(AsyncFactory.recordOperation(sysOPerLog));
        }catch (Exception exp) {

            LOGGER.error("message {}", exp.getMessage());

        }finally {

            TIME_LOCAL.remove();
        }
    }
}
